package cn.anc.aonicardv.module.ui.recorder;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.AllSelectEvent;
import cn.anc.aonicardv.event.CancelEvent;
import cn.anc.aonicardv.event.DeleteEvent;
import cn.anc.aonicardv.event.DownLoadEvent;
import cn.anc.aonicardv.event.EditEnableEvent;
import cn.anc.aonicardv.event.EditEvent;
import cn.anc.aonicardv.event.MoveEvent;
import cn.anc.aonicardv.event.RecorderEventDataEvent;
import cn.anc.aonicardv.event.RecorderPhotoDataEvent;
import cn.anc.aonicardv.event.RecorderVideoDataEvent;
import cn.anc.aonicardv.event.SelectEvent;
import cn.anc.aonicardv.module.adpter.recorder.RecorderAlbumAdapter;
import cn.anc.aonicardv.module.ui.MainActivity;
import cn.anc.aonicardv.module.ui.base.BaseActivity;
import cn.anc.aonicardv.util.AoniBeanParseUtils;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.UIUtil;
import cn.anc.aonicardv.widget.ControlSlideViewPager;
import cn.anc.aonicardv.widget.CustomDialog;
import cn.anc.aonicardv.widget.RecorderEditPopWindow;
import cn.anc.aonicardv.widget.WarningDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;

/**
 * Created by yangdai on 2017/5/23.
 */

public class RecorderAlbumActivity extends BaseActivity implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener, RecorderEditPopWindow.OnEditListener, CarControl.OnCarControlCallback, CarControl.OnHeartBeatCallBack, View.OnClickListener {

    @BindView(R2.id.tl_album)
    TabLayout albumTl;
    @BindView(R2.id.vp_album)
    ControlSlideViewPager albumVp;
    @BindView(R2.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R2.id.tv_right_text)
    TextView rightTv;
    @BindView(R2.id.tv_title)
    TextView titleTv;
    @BindView(R2.id.tv_back)
    LinearLayout backTv;
    @BindView(R2.id.tv_left)
    TextView leftTv;
    private int count;
    private RecorderAlbumAdapter albumAdapter;
    private RecorderEditPopWindow editPopWindow;
    private List<VideoBean> videoBeanList;
    private List<VideoBean> eventVideoBeanList;
    private List<PhotoBean> photoBeanList;
    private Dialog progressDialog;
    private WarningDialog warningDialog;
    private boolean isDestroy;
    private DialogUtils dialogUtils;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_recorder_album);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initVariable() {
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getCustomProgressDialog(this);
        warningDialog = dialogUtils.getWarningDialog(this);
        albumAdapter = new RecorderAlbumAdapter(getSupportFragmentManager(), this);
        editPopWindow = new RecorderEditPopWindow(getWindow().getWindowManager().getDefaultDisplay().getWidth(), ViewPager.LayoutParams.WRAP_CONTENT, this, false);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            int width = albumVp.getMeasuredWidth();
            int height = albumVp.getMeasuredHeight();
            Log.e("==========", "onWindowFocusChanged  width = " + width + " ; height = " + height);
            int dpInt = UIUtil.px2dip(width - 20) - 157;
            Log.e("==========", "onWindowFocusChanged  dpInt = " + dpInt / 3);
        }
    }

    @Override
    public void setListener() {
        albumTl.addOnTabSelectedListener(this);
        editPopWindow.setOnEditListenr(this);
        albumVp.addOnPageChangeListener(this);
        warningDialog.okTv.setOnClickListener(this);
        albumVp.setAdapter(albumAdapter);
        albumTl.setVisibility(View.VISIBLE);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        albumVp.measure(w, h);
        int height = albumVp.getMeasuredHeight();
        int width = albumVp.getMeasuredWidth();
        LogUtil.e("llcTest", "-------1--width-------:" + width);
        LogUtil.e("llcTest", "-------1--height-------:" + height);
    }

    @Override
    public void initData() {
        rightTv.setVisibility(View.VISIBLE);
        rightTv.setText(R.string.select);
        titleTv.setVisibility(View.GONE);
        progressDialog.setCancelable(true);
        progressDialog.show();
        albumTl.setupWithViewPager(albumVp);
        isDestroy = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CarControl.setOnHeartBeatCallBack(this);
        if (!CarControl.IsConnected.get()){
            if (null != warningDialog) {
                if (warningDialog.isShowing()) {
                    warningDialog.dismiss();
                }
                if (!warningDialog.isShowing() && !isDestroyed()) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }

            }
        }

    }

    @OnClick(R2.id.tv_left)
    public void allSelect() {
        if (!rightTv.getText().toString().equals(getString(R.string.select))) {
            if (leftTv.getText().toString().equals(getString(R.string.all_select))) {
                leftTv.setText(getString(R.string.cancel_all_select));
                EventBus.getDefault().post(new AllSelectEvent(true));
                count = getMediaNum();
                editPopWindow.setEnable(true);
            } else {
                count = 0;
                leftTv.setText(getString(R.string.all_select));
                EventBus.getDefault().post(new AllSelectEvent(false));
                editPopWindow.setEnable(false);
            }
            titleTv.setText(getString(R.string.selected) + count);
        }
    }

    @OnClick(R2.id.tv_back)
    public void back() {
        exit();
    }

    private int getMediaNum() {
        int count = 0;
        if (albumVp.getCurrentItem() == 0) {
            RecorderVideoFragment p = (RecorderVideoFragment) albumAdapter.getItem(0);
            count = p.getVideoNum();
        } else if (albumVp.getCurrentItem() == 1) {

            RecorderUrgentFragment p = (RecorderUrgentFragment) albumAdapter.getItem(1);
            count = p.getVideoNum();
        } else if (albumVp.getCurrentItem() == 2) {

            RecorderPhotoFragment p = (RecorderPhotoFragment) albumAdapter.getItem(2);
            count = p.getPhotoNum();
        }
        return count;
    }

    @OnClick(R2.id.tv_right_text)
    public void select() {
        count = getMediaNum();
        if (count == 0)
            return;
        if (rightTv.getText().toString().equals(getString(R.string.select))) {
            enterEdit();
        } else {
            exitEdit();
        }
    }

    private void enterEdit() {
        albumVp.setScroll(false);
        rightTv.setText(getString(R.string.exit));
        leftTv.setText(getString(R.string.all_select));
        backTv.setVisibility(View.GONE);
        leftTv.setVisibility(View.VISIBLE);
        albumTl.setVisibility(View.GONE);
        titleTv.setVisibility(View.VISIBLE);
        editPopWindow.showAtLocation(rootLayout, Gravity.BOTTOM, 0, 0);
        EventBus.getDefault().post(new EditEvent(true));
        count = 0;
        titleTv.setText(getString(R.string.selected) + count);
    }

    private void exitEdit() {
        albumVp.setScroll(true);
        rightTv.setText(getString(R.string.select));
        editPopWindow.setEnable(false);
        editPopWindow.setShareEnable(false);
        backTv.setVisibility(View.VISIBLE);
        leftTv.setVisibility(View.GONE);
        albumTl.setVisibility(View.VISIBLE);
        titleTv.setVisibility(View.GONE);
        editPopWindow.dismiss();
        EventBus.getDefault().post(new EditEvent(false));
        EventBus.getDefault().post(new AllSelectEvent(false));
        count = 0;
    }

    private long lastTime = 0;

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case 0:
                albumVp.setCurrentItem(0);
                editPopWindow.setShareVisible(true);
                LogUtil.e("llcTest", "-------onTabSelected---:0");
                if (videoBeanList == null) {
                    lastTime = DateUtils.getCurrentDateTimeNills();
                    LogUtil.e("llcTest", "-------获取视频开始时间---:" + lastTime);
                    progressDialog.show();
                    CarControl.doGetFileList(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, this);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (videoBeanList == null) {
                                videoBeanList = new ArrayList<>();
                                EventBus.getDefault().postSticky(new RecorderVideoDataEvent(videoBeanList));
                                progressDialog.dismiss();
                            }
                        }
                    }, 60000);

                }
                break;
            case 1:
                albumVp.setCurrentItem(1);
                editPopWindow.setShareVisible(false);
                LogUtil.e("llcTest", "-------onTabSelected---:1---------isMove-:" + isMove);
                if (isMove || eventVideoBeanList == null) {
                    isMove = false;
                    lastTime = DateUtils.getCurrentDateTimeNills();
                    LogUtil.e("llcTest", "-------获取紧急视频开始时间---:" + lastTime);
                    progressDialog.show();
                    CarControl.doGetFileList(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_EVENT_VIDEO, this);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (eventVideoBeanList == null) {
                                eventVideoBeanList = new ArrayList<>();
                                EventBus.getDefault().postSticky(new RecorderEventDataEvent(eventVideoBeanList));
                                progressDialog.dismiss();
                            }
                        }
                    }, 60000);
                }
                break;
            case 2:
                albumVp.setCurrentItem(2);
                editPopWindow.setShareVisible(false);
                LogUtil.e("llcTest", "-------onTabSelected---:2");
                if (photoBeanList == null) {
                    lastTime = DateUtils.getCurrentDateTimeNills();
                    LogUtil.e("llcTest", "-------获取图片开始时间---:" + lastTime);
                    progressDialog.show();
                    CarControl.doGetFileList(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_PHOTO, this);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (photoBeanList == null) {
                                photoBeanList = new ArrayList<>();
                                EventBus.getDefault().postSticky(new RecorderPhotoDataEvent(photoBeanList));
                                progressDialog.dismiss();
                            }
                        }
                    }, 60000);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    @Override
    public void delete() {
        if (count == 0) {
            Toast.makeText(this, getString(R.string.select_hint), Toast.LENGTH_LONG).show();
            return;
        }
        showDeleteDialog();
    }


    private CustomDialog mDeleteDialog, mMoveDialog;

    public void showDeleteDialog() {

        if (mDeleteDialog == null) {
            mDeleteDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.delete_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(new DeleteEvent());
                            exitEdit();
                            dialog.dismiss();

                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mDeleteDialog.setCancelable(true);
            mDeleteDialog.setCanceledOnTouchOutside(true);
        }
        mDeleteDialog.show();


    }

    public void showMoveDialog() {

        if (mMoveDialog == null) {
            mMoveDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.move_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            isMove = true;
                            EventBus.getDefault().post(new MoveEvent());
                            exitEdit();
                            dialog.dismiss();

                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mMoveDialog.setCancelable(true);
            mMoveDialog.setCanceledOnTouchOutside(true);
        }
        mMoveDialog.show();


    }


    @Override
    public void download() {
        EventBus.getDefault().post(new DownLoadEvent());
        exitEdit();
    }

    @Override
    public void cancel() {
        EventBus.getDefault().post(new CancelEvent());
        exitEdit();
    }

    private boolean isMove = false;

    @Override
    public void share() {
        if (albumVp.getCurrentItem() == 0) {
            //移动当前所选视频
            if (count == 0) {
                Toast.makeText(this, getString(R.string.select_hint), Toast.LENGTH_LONG).show();
                return;
            }
            showMoveDialog();


        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectEvent event) {
        if (event.isSelect) {
            count++;
        } else
            count--;
        titleTv.setText(getString(R.string.selected) + count);
        if (count > 0) {
            editPopWindow.setEnable(true);
            editPopWindow.setShareEnable(true);
        } else {
            editPopWindow.setEnable(false);
            editPopWindow.setShareEnable(false);
        }
        if (count == getMediaNum())
            leftTv.setText(getString(R.string.cancel_all_select));
        else {
            leftTv.setText(getString(R.string.all_select));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EditEnableEvent event) {
        if (event.isEnable)
            rightTv.setEnabled(true);
        else
            rightTv.setEnabled(false);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_DRAGGING) {
            CarControl.doStopGetThumbnail();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.post(finishRunnable);
        EventBus.getDefault().unregister(this);
        EventBus.getDefault().removeAllStickyEvents();
        isDestroy = true;
        isExit = false;
        progressDialog.dismiss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (editPopWindow.isShowing())
                exitEdit();
            else {
                exit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        CarControl.doStopGetThumbnail();
        progressDialog.setOnKeyListener(null);
        progressDialog.show();
        isExit = true;
        mHandler.post(finishRunnable);
    }

    private boolean isExit = false;
    //定时器，每隔2s执行一次该线程，知道指令返回成功或者记录仪断连为止
    private Runnable finishRunnable = new Runnable() {
        @Override
        public void run() {
            if (isExit) {
                Log.e("llc_exit", "-----------------------isExit--:" + isExit);
                CarControl.doStopAccessFiles(RecorderAlbumActivity.this);
                mHandler.postDelayed(this, 2000);
            }
        }
    };

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        LogUtil.e("aoni123", "--退出记录仪相册返回---info-------:" + info.toString());
        if (isDestroy)
            return;
        switch (info.msg_id) {
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_GET_FILE_LIST:
                if (info.rval < 0) {
                    videoBeanList = AoniBeanParseUtils.getVideoListByVideoMediaInfo(info.param);
                    EventBus.getDefault().postSticky(new RecorderVideoDataEvent(videoBeanList));
                    eventVideoBeanList = AoniBeanParseUtils.getVideoListByVideoMediaInfo(info.param);
                    EventBus.getDefault().postSticky(new RecorderEventDataEvent(eventVideoBeanList));
                    photoBeanList = AoniBeanParseUtils.getPhotoListByPhotoMediaInfo(info.param);
                    EventBus.getDefault().postSticky(new RecorderPhotoDataEvent(photoBeanList));
                } else {
                    if (CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO.equals(info.type)) {
                        long currentTime = DateUtils.getCurrentDateTimeNills();
                        LogUtil.e("llcTest", "-------获取视频结束时间---:" + currentTime);
                        LogUtil.e("llcTest", "-------获取视频时间---:" + (currentTime - lastTime));
                        LogUtil.e("llcTest", "获取视频时间:" + info.param);
                        videoBeanList = AoniBeanParseUtils.getVideoListByVideoMediaInfo(info.param);
                        EventBus.getDefault().postSticky(new RecorderVideoDataEvent(videoBeanList));
                        LogUtil.writeFile("llcTest", info.param);
                    } else if (CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_EVENT_VIDEO.equals(info.type)) {
                        long currentTime = DateUtils.getCurrentDateTimeNills();
                        LogUtil.e("llcTest", "-------获取紧急视频结束时间---:" + currentTime);
                        LogUtil.e("llcTest", "-------获取紧急视频时间---:" + (currentTime - lastTime));
                        LogUtil.e("llcTest", "获取紧急视频时间:" + info.param);
                        eventVideoBeanList = AoniBeanParseUtils.getVideoListByVideoMediaInfo(info.param);
                        EventBus.getDefault().postSticky(new RecorderEventDataEvent(eventVideoBeanList));
                    } else if (CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_PHOTO.equals(info.type)) {
                        long currentTime = DateUtils.getCurrentDateTimeNills();
                        LogUtil.e("llcTest", "-------获取图片结束时间---:" + currentTime);
                        LogUtil.e("llcTest", "-------获取图片时间---:" + (currentTime - lastTime));
                        LogUtil.e("llcTest", "获取图片:" + info.param);
                        photoBeanList = AoniBeanParseUtils.getPhotoListByPhotoMediaInfo(info.param);
                        EventBus.getDefault().postSticky(new RecorderPhotoDataEvent(photoBeanList));
                    }
                }
                progressDialog.dismiss();
                break;
            case CarControlCommand.CAR_CONTROL_COMMAND_END_ACCESS_FILES:
                isExit = false;
                //关闭退出指令定时器
                mHandler.removeCallbacks(finishRunnable);
                progressDialog.dismiss();
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
    }

    @Override
    public void OnHeartBeatConnectFail() {
    }

    @Override
    public void OnHeartBeatDisconnect() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != warningDialog) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }
        }, 500);

    }

    @Override
    public void onClick(View v) {
        warningDialog.dismiss();
        startActivity(new Intent(this, MainActivity.class));
    }
}
